package cn.codeforfun.config;

import org.springframework.boot.autoconfigure.AutoConfigurationImportSelector;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author wangbin
 */

public class TokenStoreConfiguration {

    @Configuration
    @Profile("redis_disable || unit-test")
    @EnableAutoConfiguration
    @Import(DefaultTokenStoreConfiguration.class)
    public static class DefaultTokenStoreConfiguration extends AutoConfigurationImportSelector {
        @Override
        protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
            Set<String> exclusions = super.getExclusions(metadata, attributes);
            exclusions.add("org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration");
            return exclusions;
        }

        @Bean
        public TokenStore tokenStore() {
            return new InMemoryTokenStore();
        }
    }

    @Configuration
    @Profile("redis_enable")
    public static class RedisTokenStoreConfiguration {
        @Resource
        private RedisConnectionFactory redisConnectionFactory;

        @Bean
        public TokenStore tokenStore() {
            return new RedisTokenStore(redisConnectionFactory);
        }
    }


}
